/*
 * @Author: 四川华西绿舍建材有限公司
 * @Date: 2023-10-22 16:50:53
 * @LastEditors: 陈波
 * @LastEditTime: 2024-02-29 22:15:41
 * @Description: 
 * @FilePath: \graDesign\src\store\login.ts
 */
import { defineStore } from "pinia";
import storageFn from "@/utils/storage";
import loginApi from "@/request/api/login";

const TOKEN_KEY = 'access-token'
const USER_KEY = 'userInfo'

const useLoginStore = defineStore("login", {
  state: () => {
    return {
      token: '',
      userInfo: storageFn.getStorage('local', USER_KEY) || {}
    }
  },
  getters: {
    getToken(): string {
      if(storageFn.getStorage('local', TOKEN_KEY)) {
        this.token = storageFn.getStorage('local', TOKEN_KEY);
      }
      return this.token;
    }
  },
  actions: {
    setToken(token: string) {
      this.token = token;
      storageFn.setStorage('local', TOKEN_KEY, token);
    },
    removeToken() {
      this.token = '';
      storageFn.removeStorage('local', TOKEN_KEY);
    },
    removeUserInfo() {
      this.userInfo = {};
      storageFn.removeStorage('local', USER_KEY);
    },
    getAndSetUserInfo() {
      return new Promise((resolve) => {
        loginApi.getUserInfo().then(res => {
          this.userInfo = res.data;
          // // 创建一个Blob对象
          // let blob = new Blob([res.data]);
          // // 创建一个URL.createObjectURL()方法生成的链接指向该Blob对象
          // let imageUrl = window.URL.createObjectURL(blob);
          // this.userInfo.avatar = imageUrl;
  
          storageFn.setStorage('local', USER_KEY, res.data);
          resolve(res)
        });
      })
    }
  }
});

export default useLoginStore;
